package com.ff.kvm.mall.service.impl;

import com.ff.kvm.common.dv.team.TeamPageDV;
import com.ff.kvm.common.dv.team.TeamUserDV;
import com.ff.kvm.common.dv.es.UserESDV;
import com.ff.kvm.common.dv.product.BuyProductDV;
import com.ff.kvm.common.dv.shopping.CheckOrderResultDV;
import com.ff.kvm.common.dv.user.DealPwdDV;
import com.ff.kvm.common.dv.user.UpdateDealPwdDV;
import com.ff.kvm.common.dv.user.UserInfoDV;
import com.ff.kvm.common.eunm.*;
import com.ff.kvm.common.third_util.WXPublicUtil;
import com.ff.kvm.common.util.Constants;
import com.ff.kvm.common.util.MyUtil;
import com.ff.kvm.common.vo.PageResult;
import com.ff.kvm.common.vo.Response;
import com.ff.kvm.dao.mapper.PersonalGiftMapper;
import com.ff.kvm.dao.mapper.UserDirectMapper;
import com.ff.kvm.dao.mapper.UserMapper;
import com.ff.kvm.dao.model.PersonalGift;
import com.ff.kvm.dao.model.User;
import com.ff.kvm.dao.model.UserDirect;
import com.ff.kvm.mall.helper.SpreadHelper;
import com.ff.kvm.mall.service.*;
import com.ff.kvm.team.consumer.TeamConsumer;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;


@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;


    @Autowired
    private AccountService accountService;

    @Autowired
    private OrderItemsService orderItemsService;

    @Autowired
    private TeamConsumer teamConsumer;

    @Autowired
    private UserDirectMapper userDirectMapper;

    @Autowired
    private RedisService redisService;

    @Autowired
    private ProductService productService;

    @Autowired
    private PersonalGiftMapper personalGiftMapper;

    @Autowired
    private SpreadHelper spreadHelper;

    @Value("${spring.profiles.active}")
    private String act;




    @Override
    public Boolean isExistsBlack(int userId) {
        Integer isExists = userMapper.isExistsBlack(userId);
        if (isExists != null) {
            return true;
        }
        return false;
    }

    @Override
    public User findUserById(int userId) {
        return userMapper.selectByPrimaryKey(userId);
    }

    @Override
    public User findUserByUserCode(String userCode) {
        return userMapper.findUserByUserCode(userCode);
    }

    @Override
    public int upLv(int userId,int orderId) {
        User user = userMapper.selectByPrimaryKey(userId);
        Integer upUserId = userMapper.getIdByUserCode(user.getPollCode());
        int lv = orderItemsService.findGiftLvByOrderId(orderId);
        userMapper.upLv(userId,lv);
        sendUserMsg(user,upUserId==null?0:upUserId,lv);

        return lv;
    }

    @Override
    public Integer findUpUserLvById(int userId) {

        return userMapper.findUpUserLvById(userId);
    }

    @Override
    public User findUpUserById(int userId) {
        return userMapper.findUpUserById(userId);
    }

    @Override
    public int getFloorByUserCode(String userCode) {
        return userMapper.getFloorByUserCode(userCode);
    }

    @Override
    public void saveUserES(User user,int upUserId) {
        UserESDV userESDV = new UserESDV();
        userESDV.setUserId(user.getId());
        userESDV.setUpUserId(upUserId);
        userESDV.setLv(user.getLv());
        userESDV.setFloor(user.getFloor());
        userESDV.setCreateTime(new Date());
        teamConsumer.addUser(userESDV);
    }

    @Override
    public Integer getIdByUserCode(String userCode) {
        return userMapper.getIdByUserCode(userCode);
    }

    @Override
    public void updateLoginTime(int id) {
        userMapper.updateLoginTime(id);
    }

    @Override
    public Integer getIdByOpOpenId(String opOpenId) {
        return userMapper.getIdByOpOpenId(opOpenId);
    }

    @Override
    public String getSpreadUrlByUserId(int userId) {
        return userMapper.getSpreadUrlByUserId(userId);
    }

    @Override
    public void saveUser(User user) {
        userMapper.insert(user);
    }

    @Override
    public User findUserByMobile(String mobile) {
        return userMapper.findUserByMobile(mobile);
    }

    @Override
    public Integer getUserIdByMobile(String mobile) {

        return userMapper.getUserIdByMobile(mobile);
    }

    @Override
    public void updateLoginPwd(int id, String loginPwd) {
        userMapper.updateLoginPwd(id, loginPwd);
    }

    @Override
    public int createUser(User user) {
        userMapper.insert(user);
        accountService.createAccount(user.getId());
        return user.getId();
    }

    @Override
    public int getUserLvByUserId(int userId) {
        return userMapper.getUserLvByUserId(userId);
    }

    @Override
    public Response<Boolean> checkMobile(String mobile) {
        Response<Boolean> response = new Response<>();
        Integer id = userMapper.getUserIdByMobile(mobile);
        if(id == null){
            response.setData(false);
            response.setCode(StatusEnum.SUCCESS.code());
            response.setMsg(StatusEnum.SUCCESS.description());
            return response;
        }
        response.setData(true);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Transactional
    @Override
    public Response<CheckOrderResultDV> directGift(int userId, int productId) {
        Response<CheckOrderResultDV> response = new Response<>();
        String[] direct = redisService.getCache(Constants.USER_GIFT).split("-");
        List<UserDirect> list = userDirectMapper.findByUserId(userId);
        if(list.size() < Integer.valueOf(direct[0])){
            response.setCode(StatusEnum.NOT_DIRECT_USER.code());
            response.setMsg(StatusEnum.NOT_DIRECT_USER.description());
            return response;
        }
        for(int i=0;i<3;i++){
            UserDirect userDirect = list.get(i);
            userDirect.setStatus(1);
            userDirectMapper.updateByPrimaryKey(userDirect);
        }

        BuyProductDV buyProductDV = new BuyProductDV();
        buyProductDV.setUserId(userId);
        buyProductDV.setId(Integer.valueOf(direct[1]));
        buyProductDV.setQuantity(Integer.valueOf(direct[2]));

        return productService.buyProduct(buyProductDV);

    }

    @Override
    public void sendUserMsg(User user, int upId,int lv) {

        UserESDV userESDV = new UserESDV();
        userESDV.setUserId(user.getId());
        userESDV.setUpUserId(upId);
        userESDV.setLv(lv);
        userESDV.setFloor(user.getFloor());
        userESDV.setCreateTime(new Date());
        teamConsumer.addUser(userESDV);
    }

    @Transactional
    @Override
    public Response<Boolean> bindPhone(int userId,String mobile) {
        Response<Boolean> response = new Response<>();
        userMapper.bindPhone(userId,mobile);

        response.setData(true);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Override
    public Response<PageResult<TeamUserDV>> teamUser(TeamPageDV teamPageDV) {
        Response<PageResult<TeamUserDV>> response = new Response<>();
        int pageSize = Integer.valueOf(redisService.getCache(Constants.PAGE_SIZE));
        List<TeamUserDV> listDV = new ArrayList<>();
        Page page = PageHelper.startPage(teamPageDV.getPageNum(),pageSize);
        List<User> list = userMapper.findDirectUser(teamPageDV.getUserId(),teamPageDV.getLv(),teamPageDV.getType());
        for(User user : list){
            TeamUserDV teamUserDV = new TeamUserDV();
            teamUserDV.setUserId(user.getId());
            teamUserDV.setName(user.getName());
            teamUserDV.setMobile(user.getMobile());
            teamUserDV.setCreateTime(MyUtil.formatDateYMDhms(user.getCreateTime()));
            listDV.add(teamUserDV);
        }
        PageResult<TeamUserDV> result = new PageResult<>();
        result.setPageSize(pageSize);
        result.setTotal(page.getTotal());
        result.setData(listDV);
        response.setData(result);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Override
    public String getNameByUserId(int userId) {
        return userMapper.getNameByUserId(userId);
    }

    @Override
    public User findNormalUser(int userId) {
        return userMapper.findNormalUser(userId);
    }

    @Override
    public Response<Boolean> updateDealPwd(UpdateDealPwdDV updateDealPwdDV) {
        Response<Boolean> response = new Response<>();
        String dealPwd = userMapper.getDealPwdById(updateDealPwdDV.getUserId());
        if(!dealPwd.equals(MyUtil.MD5encode(updateDealPwdDV.getOldDealPwd()))){
            response.setData(false);
            response.setCode(StatusEnum.PWD_ERROR.code());
            response.setMsg(StatusEnum.PWD_ERROR.description());
            return response;
        }
        userMapper.updateDealPwd(updateDealPwdDV.getUserId(),MyUtil.MD5encode(updateDealPwdDV.getNewDealPwd()));

        response.setData(true);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }



    @Override
    public Response<Boolean> forgetDealPwd(int userId,String dealPwd) {
        Response<Boolean> response = new Response<>();
        userMapper.updateDealPwd(userId,MyUtil.MD5encode(dealPwd));
        response.setData(true);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Override
    public Response<String> getMobile(int userId) {
        Response<String> response = new Response<>();
        String mobile = userMapper.getMobileById(userId);
        if(MyUtil.isBlank(mobile)){
            response.setCode(StatusEnum.FAIL.code());
            response.setMsg(StatusEnum.FAIL.description());
            return response;
        }
        response.setData(mobile);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Override
    public Response<UserInfoDV> userInfo(int userId) {
        Response<UserInfoDV> response = new Response<>();
        User user = userMapper.userInfo(userId);
        UserInfoDV userInfoDV = new UserInfoDV();
        userInfoDV.setRealName(user.getName());
        userInfoDV.setName(user.getNickName());
        userInfoDV.setLv(user.getLv());
        userInfoDV.setMobile(user.getMobile());
        userInfoDV.setHeadUrl(user.getHeadUrl());
        if(MyUtil.isBlank(user.getDealPwd())){
            userInfoDV.setDealPwd(0);
        }else{
            userInfoDV.setDealPwd(1);
        }

        userInfoDV.setLvName(UserLvEnum.getName(user.getLv()));
        response.setData(userInfoDV);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;

    }

    @Override
    public Response<Boolean> dealPwd(DealPwdDV dealPwdDV) {
        User user = new User();
        user.setId(dealPwdDV.getUserId());
        user.setName(dealPwdDV.getName());
        user.setSex(dealPwdDV.getSex());
        user.setIdCard(dealPwdDV.getIdCard());
        user.setDealPwd(MyUtil.MD5encode(dealPwdDV.getDealPwd()));
        userMapper.updateByPrimaryKeySelective(user);
        Response<Boolean> response = new Response<>();
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }

    @Override
    public String getUserDealPwd(int userId) {
        return userMapper.getDealPwdById(userId);
    }


    @Override
    public Response<String> spreadQRCode(int userId) {
        Response<String> response = new Response<>();
        User user = userMapper.findNormalUser(userId);
        String url = user.getSpread();
        if(MyUtil.isBlank(url)){
            int type = 0;
            if(act.equals("prd")){
                type = 1;
            }
            url = WXPublicUtil.getSpreadUrl(type,user.getUserCode(),spreadHelper.getAccessToken());

            if(MyUtil.isBlank(url)){
                response.setCode(StatusEnum.DATA_ERROR.code());
                response.setMsg(StatusEnum.DATA_ERROR.description());
                return response;
            }
            userMapper.updateSpread(userId,url);

        }
        response.setData(url);
        response.setCode(StatusEnum.SUCCESS.code());
        response.setMsg(StatusEnum.SUCCESS.description());
        return response;
    }



    @Override
    public void checkDirectGift(String pollCode, int userId,String[] direct,int channel) {

        int directUser = userMapper.countDirectUser(pollCode);//统计为领取奖品的直推下级
        int giftPeople = Integer.valueOf(direct[0]);
        if(directUser < giftPeople){//小于最低领奖个数
            return;
        }
        User user = userMapper.findNormalUser(userId);
        if((directUser/giftPeople) > user.getDirectGiftTimes()){
            userMapper.addDirectGiftTimes(userId);
        }

        //发放奖品至用户礼品表
        PersonalGift personalGift = new PersonalGift();
        personalGift.setUserId(userId);
        personalGift.setGiftId(Integer.valueOf(direct[1]));
        personalGift.setGetStatus(0);
        personalGift.setCreateTime(new Date());
        personalGift.setChannel(channel);
        personalGift.setExpirationTime(MyUtil.getDate(personalGift.getCreateTime(),Integer.valueOf(direct[3])));
        personalGiftMapper.insert(personalGift);

    }

    @Override
    public Integer getUpUserId(int userId) {
        return userMapper.getUpUserId(userId);
    }

    @Override
    public Integer getIdByUnionId(String unionId) {
        return userMapper.getIdByUnionId(unionId);
    }

    @Override
    public void registerGift(int userId,String[] gift,int channle) {

        //发放奖品至用户礼品表
        PersonalGift personalGift = new PersonalGift();
        personalGift.setUserId(userId);
        personalGift.setGiftId(Integer.valueOf(gift[1]));
        personalGift.setGetStatus(0);
        personalGift.setCreateTime(new Date());
        personalGift.setChannel(channle);
        personalGift.setExpirationTime(MyUtil.getDate(personalGift.getCreateTime(),Integer.valueOf(gift[3])));
        personalGiftMapper.insert(personalGift);
    }

}
